package com.cy.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//自定义限流处理异常对象
@Component
public class ConsumerBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
//        throw e;//不处理异常

        //对异常进行处理
        //设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉浏览器向他响应的数据类型，以及以什么编码进行显示
        httpServletResponse.setContentType("text/html;charset=utf-8");
        //获取输出流
        PrintWriter out = httpServletResponse.getWriter();
        //对异常进行判断instanceof
        if(e instanceof DegradeException){
            out.println("访问服务频繁，请稍后再试！");
        }else{
            out.println("服务异常，请稍后再试！");
        }
        out.flush();
    }

}
